#pragma once

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

namespace Server
{
    enum
    {
        USAGE_ERROR = 1,
        SOCKET_ERROR,
        BIND_ERROR
    };

    static std::string defaultIp = "127.0.0.1";

    class udpServer
    {
    public:
        udpServer(const uint16_t &serverport, const std::string &serverip = defaultIp)
            : _serverip(serverip), _serverport(serverport), _sock(-1)
        {
        }

        void initServer()
        {
            // 1.
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cerr << "_sock socket error" << std::endl;
                exit(SOCKET_ERROR);
            }
            std::cout << "_sock socket success" << std::endl;
            // 2.
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_serverport);
            local.sin_addr.s_addr = inet_addr(_serverip.c_str());
            int n = bind(_sock, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                std::cerr << "_sock bind error" << std::endl;
                exit(BIND_ERROR);
            }
            std::cout << "_sock bind success" << std::endl;
        }

        void start()
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);

            char message[1024];
            while (true)
            {
                // 1. 接收
                int n = recvfrom(_sock, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
                if (n > 0)
                    message[n] = 0;
                std::cout << "debug client# " << message << std::endl;

                // 2. 处理
                // 处理一下再发送给 client

                // 3. 回送
                sendto(_sock, message, sizeof(message), 0, (struct sockaddr *)&peer, sizeof(peer));
            }
        }

        ~udpServer() {}

    private:
        int _sock;
        uint16_t _serverport;
        std::string _serverip;
    };
}
